<template>
  <div class="import">
    <h3>批量导入</h3>
    <myexcel :beforeUpload="beforeUpload" :onSuccess="onSuccess"></myexcel>
  </div>
</template>

<script>
import { importEmployeesApi } from '@/api/Employees'
export default {
  methods: {
    beforeUpload (file) {
      let less2M = file.size / 1024 / 1024 < 2
      if (!less2M) {
        this.$message.error('文件大小不能超过2MB')
      }
      return less2M
    },
    FormDate (days) {
      const mytime = (days - 1) * 24 * 60 * 60 * 1000
      const myDate = new Date(mytime)
      myDate.setFullYear(myDate.getFullYear() - 70)
      return myDate
    },
    onSuccess ({ header, results }) {
      var obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      const newobj = {}
      const newArr = results.map(item => {
        Object.keys(obj).forEach(subitem => {
          if (subitem === '入职日期' || subitem === '转正日期') {
            newobj[obj[subitem]] = this.FormDate(item[subitem])
          } else {
            newobj[obj[subitem]] = item[subitem]
          }
        })
        return newobj
      })
      importEmployeesApi(newArr)
      this.$router.push('/employees')
    }
  }
}
</script>

<style lang="scss">
.import {
  h3 {
    text-align: center;
  }
}
</style>
